package cn.time1024.time_app.push

import android.content.Context
import android.util.Log
import cn.jpush.android.api.JPushMessage
import cn.jpush.android.service.JPushMessageReceiver
import cn.jpush.android.api.CustomMessage
import cn.jpush.android.api.NotificationMessage
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import android.content.Intent
import cn.time1024.time_app.MainActivity

class MyJPushReceiver : JPushMessageReceiver() {
    override fun onAliasOperatorResult(context: Context, message: JPushMessage) {
        super.onAliasOperatorResult(context, message)
        val ok = message.errorCode == 0
        Log.d(
            "JPush",
            "[Alias] seq=${message.sequence} ok=${ok} alias=${message.alias} err=${message.errorCode}"
        )
    }

    override fun onTagOperatorResult(context: Context, message: JPushMessage) {
        super.onTagOperatorResult(context, message)
        val ok = message.errorCode == 0
        Log.d(
            "JPush",
            "[Tags] seq=${message.sequence} ok=${ok} tags=${message.tags} err=${message.errorCode}"
        )
    }

    // ====== 自定义消息（透传）到达：本地显示一条通知，便于可见化验证 ======
    override fun onMessage(context: Context, message: CustomMessage) {
        super.onMessage(context, message)
        Log.d("JPush", "[Message] content=${message.message}")
        try {
            val channelId = "jpush_custom_channel"
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val mgr = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                val ch = NotificationChannel(channelId, "JPush自定义消息", NotificationManager.IMPORTANCE_DEFAULT)
                mgr.createNotificationChannel(ch)
            }
            val notifyId = (System.currentTimeMillis() % Int.MAX_VALUE).toInt()
            val builder = NotificationCompat.Builder(context, channelId)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentTitle("收到自定义消息")
                .setContentText(message.message)
                .setAutoCancel(true)
            NotificationManagerCompat.from(context).notify(notifyId, builder.build())
        } catch (e: Throwable) {
            Log.e("JPush", "显示自定义消息通知失败", e)
        }
    }

    // ====== 通知到达与点击 ======
    override fun onNotifyMessageArrived(context: Context, message: NotificationMessage) {
        super.onNotifyMessageArrived(context, message)
        Log.d("JPush", "[NotifyArrived] title=${message.notificationTitle} content=${message.notificationContent}")
    }

    override fun onNotifyMessageOpened(context: Context, message: NotificationMessage) {
        super.onNotifyMessageOpened(context, message)
        Log.d("JPush", "[NotifyOpened] title=${message.notificationTitle} content=${message.notificationContent}")
        // 解析 extras，尝试获取 notificationId
        val extrasJson = message.notificationExtras
        var notificationId: Long? = null
        try {
            val obj = org.json.JSONObject(extrasJson ?: "{}")
            if (obj.has("notificationId")) {
                val v = obj.get("notificationId")
                notificationId = when (v) {
                    is Number -> v.toLong()
                    is String -> v.toLongOrNull()
                    else -> null
                }?.takeIf { it > 0 }
            } else if (obj.has("id")) {
                val v = obj.get("id")
                notificationId = when (v) {
                    is Number -> v.toLong()
                    is String -> v.toLongOrNull()
                    else -> null
                }?.takeIf { it > 0 }
            }
        } catch (_: Throwable) {}

        // 点击通知后唤起主页并携带内容与深链参数
        val intent = Intent(context, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.putExtra("jpush_notification_title", message.notificationTitle)
        intent.putExtra("jpush_notification_content", message.notificationContent)
        intent.putExtra("from_jpush", true)
        if (notificationId != null) intent.putExtra("notificationId", notificationId!!)
        context.startActivity(intent)
    }

    override fun onNotifyMessageDismiss(context: Context, message: NotificationMessage) {
        super.onNotifyMessageDismiss(context, message)
        Log.d("JPush", "[NotifyDismiss] title=${message.notificationTitle}")
    }

    // ====== 连接与注册事件 ======
    override fun onConnected(context: Context, isConnected: Boolean) {
        super.onConnected(context, isConnected)
        Log.d("JPush", "[Connected] isConnected=${isConnected}")
    }

    override fun onRegister(context: Context, registrationId: String) {
        super.onRegister(context, registrationId)
        Log.d("JPush", "[Register] rid=${registrationId}")
    }
}